package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.bo.ImportUserGzjlBo;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.service.ISysUserGzjlService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.ExcelUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 系统-用户工作经历
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "系统-用户工作经历接口")
@RestController
@RequestMapping("/api/spzx-spcy/sysUserGzjl")
public class SysUserGzjlController extends BaseController<SysUserGzjl, ISysUserGzjlService> {

    private static final Logger log = LoggerFactory.getLogger(SysUserGzjlController.class);

    @Resource
    private ISysUserGzjlService sysUserGzjlService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Resource
    private BusinessConstant businessConstant;


    @AutoLog(value = "用户工作经历-分页列表查询")
    @ApiOperation(value = "用户工作经历-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SysUserGzjl sysUserGzjl,
                                       @RequestParam(value = "year",defaultValue = "")String year,
                                       @RequestParam(value = "isSelectMe",defaultValue = "true")boolean isSelectMe,
                                       PageVo pageVo,
                                       OrderItemVo orderItemVo) {
        Page<SysUserGzjl> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        if (StringUtils.isNotBlank(sysUserGzjl.getFuserid())){
            isSelectMe = false;
        }
        IPage<SysUserGzjl> pageList = sysUserGzjlService.getPageList(page, sysUserGzjl, year, isSelectMe, orderItemVo);
        return HttpResult.ok(pageList);
    }

    @Log(title = "用户工作经历-所有列表")
    @ApiOperation(value = "用户工作经历-所有列表")
    @GetMapping(value = "/queryAllList")
    public HttpResult<?> queryAllList(SysUserGzjl sysUserGzjl,
                                      @RequestParam(value = "year",defaultValue = "")String year,
                                      @RequestParam(value = "isSelectMe",defaultValue = "true")boolean isSelectMe) {
        if (StringUtils.isNotBlank(sysUserGzjl.getFuserid())){
            isSelectMe = false;
        }
        List<SysUserGzjl> pageList = sysUserGzjlService.getList(sysUserGzjl, year, isSelectMe);
        return HttpResultVo.HttpResultList(pageList);
    }

    @AutoLog(value = "用户工作经历-添加")
    @ApiOperation(value = "用户工作经历-添加")
    @PostMapping(value = "/addGzjl")
    public HttpResult<?> add(@RequestBody SysUserGzjl sysUserGzjl) {
        sysUserGzjl.setId(GetUuIdUtils.ReplaceUuId());
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已过期，请重新登录");
        }
        sysUserGzjl.setId(GetUuIdUtils.ReplaceUuId());
        if (StringUtils.isBlank(sysUserGzjl.getFuserid())) {
            sysUserGzjl.setFuserid(currentUser.getId());
            sysUserGzjl.setFusermc(currentUser.getName());
        }else {
            YcSysUser user = ycSysUserService.getById(sysUserGzjl.getFuserid());
            if (user != null){
                sysUserGzjl.setFusermc(user.getRealname());
            }
        }
        sysUserGzjlService.save(sysUserGzjl);

        String operContent = "新增信息：";
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(sysUserGzjl);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_GZJL,operContent,sysUserGzjl.getId(), LogConstant.LOGS_SYS_USER_GZJL, SpcyConstant.LOGS_SYS_TYPE_XZ);

        HttpResult result = new HttpResult(true);
        result.setResult(sysUserGzjl);
        result.setMessage("添加成功");
        return result;
    }

    @AutoLog(value = "用户工作经历-编辑")
    @ApiOperation(value = "用户工作经历-编辑")
    @ApiImplicitParam(name = "id",value = "用户工作经历id",required = true)
    @PutMapping(value = "/editGzjl")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("用户工作经历信息id不能为空");
        }
        String djjxxxId = buffer.get("id");
        SysUserGzjl oldDjjbxx = sysUserGzjlService.getById(djjxxxId);
        SysUserGzjl oldDjjbxxUpdate = sysUserGzjlService.getById(djjxxxId);
        if (oldDjjbxxUpdate == null){
            return HttpResult.error("当前用户工作经历基本信息数据不存在，请重试");
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldDjjbxxUpdate, buffer);
        sysUserGzjlService.updateById(oldDjjbxxUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldDjjbxx);
        operContent += LogUtils.BeanModifyMsg(oldDjjbxxUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_GZJL,operContent,djjxxxId,LogConstant.LOGS_SYS_USER_GZJL,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    @AutoLog(value = "用户工作经历-批量删除")
    @ApiOperation(value = "用户工作经历-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SysUserGzjl> sysUserGzjls = sysUserGzjlService.listByIds(idsList);
        if (CollectionUtils.isEmpty(sysUserGzjls)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SysUserGzjl gzjl : sysUserGzjls){
            String id = gzjl.getId();
            sysUserGzjlService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(gzjl);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_GZJL,operContent,id,LogConstant.LOGS_SYS_USER_GZJL,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    @AutoLog(value = "用户工作经历-通过id查询")
    @ApiOperation(value = "系统-用户工作经历-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SysUserGzjl sysUserGzjl = sysUserGzjlService.getById(id);
        return HttpResult.ok(sysUserGzjl);
    }

    @AutoLog(value = "导入用户工作经历基本信息数据-表格excel")
    @ApiOperation(value = "导入用户工作经历基本信息数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true)
    })
    @PostMapping(value = "impGzjlData")
    public HttpResult<?> impGzjlData(@RequestParam(value = "fuserid",defaultValue = "")String userid, @RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            log.error("登录过期，导入失败");
            return HttpResult.error("登录失效，请重新登录");
        }

        String username = "";
        if (StringUtils.isBlank(userid)){
            userid = currentUser.getId();
            username = currentUser.getName();
        }else {
            YcSysUser user = ycSysUserService.getById(userid);
            username = user.getRealname();
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;

        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_SYS_GZJL_SECODE_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入用户工作基本信息数据出错-{}",e.getMessage());
        }

        List<SysUserGzjl> gzjlList = new ArrayList<>();
        for (int order=0; order<mapsList.size(); order++) {
            ImportUserGzjlBo pxjlBo = new ImportUserGzjlBo();
            BeanUtil.copyProperties(mapsList.get(order), pxjlBo);

            SysUserGzjl gzjl = new SysUserGzjl();
            gzjl.setId(GetUuIdUtils.ReplaceUuId());
            gzjl.setFuserid(userid);
            gzjl.setFusermc(username);

            gzjl.setFcsgz(pxjlBo.getFcsgz());
            gzjl.setFgzdw(pxjlBo.getFgzdw());
            gzjl.setFzw(pxjlBo.getFzw());

            if (StringUtils.isNotBlank(pxjlBo.getFgzkssj())) {
                gzjl.setFgzkssj(pxjlBo.getFgzkssj());
            }

            if (StringUtils.isNotBlank(pxjlBo.getFgzjssj())) {
                gzjl.setFgzjssj(pxjlBo.getFgzjssj());
            }
            gzjl.setCreateTime(new Date());

            gzjlList.add(gzjl);

            String operContent = "新增导入信息：";
            Map<String, Object> bhgzMap = ObjectToMapUtils.objectToMap(gzjl);
            operContent += LogUtils.MapToStringMethod(bhgzMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_GZJL,operContent,gzjl.getId(),LogConstant.LOGS_SYS_USER_GZJL,SpcyConstant.LOGS_SYS_TYPE_XZ);
        }

        if (CollectionUtil.isNotEmpty(gzjlList)) {
            sysUserGzjlService.saveBatch(gzjlList);
        }

        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    @AutoLog(value = "下载用户工作经历-导入模板")
    @ApiOperation(value = "下载用户工作经历-导入模板")
    @GetMapping("/downUserGzjlTemplate")
    public void downUserGzjlTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("userGzjlImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_SYS_GZJL_SECODE_XML, out);
        } catch (Exception e) {
            log.error("下载用户工作经历模板错误-{}",e.getMessage());
        }
    }

    @AutoLog(value = "导出用户工作经历数据-表格excel")
    @ApiOperation(value = "导出用户工作经历数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "id字符逗号分割",dataType = "String"),
            @ApiImplicitParam(name = "year",value = "年份",dataType = "String"),
            @ApiImplicitParam(name = "isExportMe",value = "默认导出所有，导入个人值为[是]",dataType = "String")
    })
    @GetMapping("/exportUserGzjlData")
    public void exportUserGzjlData(@RequestParam(value = "ids",defaultValue = "")String ids,
                   SysUserGzjl gzjl,
                   @RequestParam(value = "year",defaultValue = "")String year,
                   @RequestParam(value = "isExportMe",defaultValue = "true")boolean isExportMe,
                   HttpServletResponse response){

        List<List<String>> resultList = new ArrayList<>();

        // 表头
        String[] titles = new String[]{"序号","姓名","单位名称","工作开始时间(YYYY-MM-DD)","工作结束时间(YYYY-MM-DD)","工作岗位","职务"};
        List<String> titleList = CollectionUtil.newArrayList(titles);
        resultList.add(titleList);

        List<SysUserGzjl> gzjlList = new ArrayList<>();

        // 多选导出
        if (StringUtils.isNotEmpty(ids)) {
            List<String> IdsList = StringPatternUtils.getListByIds(ids);
            gzjlList = sysUserGzjlService.listByIds(IdsList);
        }else {
            if (StringUtils.isNotBlank(gzjl.getFuserid())){
                isExportMe = false;
            }
            gzjlList = sysUserGzjlService.getList(gzjl, year, isExportMe);
        }

        for (int i = 0; i<gzjlList.size(); i++){
            // 数据
            List<String> dataList = new ArrayList<>();

            dataList.add(String.valueOf(i+1));
            dataList.add(gzjlList.get(i).getFusermc());
            dataList.add(gzjlList.get(i).getFgzdw());

            if (gzjlList.get(i).getFgzkssj() != null) {
                dataList.add(gzjlList.get(i).getFgzkssj());
            }else {
                dataList.add("");
            }

            if (gzjlList.get(i).getFgzjssj() != null) {
//                dataList.add(DateConversionUtils.DateToStringYYYYMMDD(gzjlList.get(i).getFgzjssj()));
                dataList.add(gzjlList.get(i).getFgzjssj());
            }else {
                dataList.add("");
            }

            dataList.add(gzjlList.get(i).getFcsgz());
            dataList.add(gzjlList.get(i).getFzw());

            resultList.add(dataList);
        }

        // 文件名称
        String title = "工作经历基础信息";

        String rootUrl = localFileUploadUtils.getTempFileRootUrl();

        File outFile = ExcelUtils.getLocalDempXlsExcel(resultList, title, rootUrl);

        localFileUploadUtils.ejzLocalFileByZdyFile(outFile,response);
    }
}
